package com.tzxs.pay.main.gather;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.text.Html;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tzxs.pay.AlipayZoloz;
import com.tzxs.pay.AppAuthTokenGettingReply;
import com.tzxs.pay.PayingWithFaceReply;
import com.tzxs.pay.R;
import com.tzxs.pay.ZimDataGetter;
import com.tzxs.pay.ZolozConstants;
import com.tzxs.pay.databinding.FragmentGeneralBinding;
import com.tzxs.pay.main.baiduvoice.BaiduSpeechClient;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.base.OnMultiClickListener;
import com.tzxs.pay.main.bill.detail.AutTncActivity;
import com.tzxs.pay.main.bill.detail.CollAndInstallDetailActivity;
import com.tzxs.pay.main.bill.viewmodel.BillViewModel;
import com.tzxs.pay.main.gather.model.BankBean;
import com.tzxs.pay.main.gather.model.ScanPayBean;
import com.tzxs.pay.main.gather.viewmodel.BankViewModel;
import com.tzxs.pay.main.onlineaut.AmountFilter;
import com.tzxs.pay.main.print.utils.print.AidlUtil;
import com.tzxs.pay.util.ApiService;
import com.tzxs.pay.util.ClickUtil;
import com.tzxs.pay.util.ISharedPreference;
import com.tzxs.pay.util.PrintCommands;
import com.tzxs.pay.util.ScanActivity;
import com.tzxs.pay.util.StatusBarColorSetter;
import com.tzxs.pay.util.SystemUtil;
import com.tzxs.pay.util.ViewDialog;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

//import com.tzxs.pay.main.broadcast_receiver.ScannedResultBroadcastReceiver;

public class GeneralActivity extends BaseActivity<FragmentGeneralBinding> {
    private GeneralActivity currentContext = this;
    private AlipayZoloz alipayZoloz;
    private HashMap merchantInfo;
    private static final String MERCHANT_ID = "2088721418280155";
    private static final String APP_ID = "2017031806275797";

//    private static final String APP_ID ="2018022602275094";

    //    private static final String PRIVATE_KEY = "Your private key";
    private static final String DEVICE_NUMBER = "Your device number";
    /****测试前置摄像头扫码付款，发布时注释****/
//    private ScannedResultBroadcastReceiver scannedResultBroadcastReceiver = new ScannedResultBroadcastReceiver() {
//        @Override
//        protected void handleScannedResult(Bundle bundle) {
//            scanPay(bundle);
//        }
//    };
    /****************************************/
    private OnMultiClickListener onMultiClickListener = new OnMultiClickListener() {
        @Override
        public void onMultiClick(View v) {
            Intent intent;
            switch (v.getId()) {
                //扫一扫查询订单
                case R.id.sweep:
                    requestScanPermission(SCAN_CODE);
                    break;
                //收款列表
                case R.id.collection_list:
                    intent = new Intent(GeneralActivity.this, GatherListActivity.class);
                    startActivity(intent);
                    break;
                //普通收款查询
                case R.id.collection_search:
                    intent = new Intent(GeneralActivity.this, SearchGaActivity.class);
                    startActivity(intent);
                    break;
                //扫码收款
                case R.id.sweep_receive:
                    if (TextUtils.isEmpty(dataBinding.generalCount.getText().toString())) {
                        Snackbar.make(v, "请输入收款金额！", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                    requestScanPermission(SCAN_PAY_CODE);  //发布时解除注释
                    /****测试前置摄像头扫码付款，发布时注释****/
//                    try {
//                        AidlUtil.getInstance().scanDecoder();
//                    } catch (RemoteException ex) {
//                        ex.printStackTrace();
//                    }
                    /****************************************/
                    break;
                case R.id.bank_card_receive:
                    if (TextUtils.isEmpty(dataBinding.generalCount.getText().toString())) {
                        Snackbar.make(v, "请输入收款金额！", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                    if (!ClickUtil.isFasClick()) {
                        Map<String, String> map = new HashMap<>();
                        bankViewModel.createBankOrder(Double.parseDouble(dataBinding.generalCount.getText().toString()),
                                "pay", dataBinding.generalNote.getText().toString(),
                                0, "0", () -> {
//                            dialog.dismiss();
                                    Log.d(TAG, "onClick: 创建普通收款订单成功：");
                                    startGather();
                                });
                    }
                    //创建普通银行卡收款订单
                    break;
                case R.id.receiveMoneyWithFaceTextView:
                    String amount = dataBinding.generalCount.getText().toString();
                    if (amount.isEmpty()) {
                        Toast.makeText(currentContext, "请输入收款金额！", Toast.LENGTH_SHORT).show();
                    } else {
                        String remarks = dataBinding.generalNote.getText().toString();
                        if (remarks.isEmpty()) {
                            Toast.makeText(currentContext, "备注不能为空", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        alipayZoloz.getMetaInfo(merchantInfo, new AlipayZoloz.Callback() {
                            @Override
                            public void onSuccess(String metaInfo) {
                                ApiService apiService = new Retrofit.Builder().baseUrl(ApiService.baseUrl).addConverterFactory(GsonConverterFactory.create())
                                        .build().create(ApiService.class);
                                String token = ISharedPreference.getInstance(getApplication()).getToken();
                                apiService.getAppAuthToken(token).enqueue(new Callback<AppAuthTokenGettingReply>() {
                                    @Override
                                    public void onResponse(Call<AppAuthTokenGettingReply> call, Response<AppAuthTokenGettingReply> response) {
                                        AppAuthTokenGettingReply reply = response.body();
                                        if (reply.code.equals("10001")) {
                                            Log.d(TAG, "reply.data.data.rsaPrivateKey: " + reply.data.data.rsaPrivateKey);
                                            Log.d(TAG, "reply.data.app_auth_token: " + reply.data.data.app_auth_token);
                                            Log.d(TAG, "APP_ID: " + APP_ID);
                                            new ZimDataGetter(currentContext).getZimData(APP_ID, reply.data.data.rsaPrivateKey,
                                                    reply.data.data.app_auth_token, metaInfo, new ZimDataGetter.Callback() {
                                                        @Override
                                                        public void onSuccess(String zimId, String zimInitClientData) {
                                                            HashMap params = new HashMap();
                                                            params.put("zim.init.resp", zimInitClientData);
                                                            alipayZoloz.verify(zimId, params, new AlipayZoloz.Callback() {
                                                                @Override
                                                                public void onSuccess(String ftoken) {
                                                                    Log.d(TAG, "token: " + token);
                                                                    Log.d(TAG, "ftoken: " + ftoken);
                                                                    Log.d(TAG, "amount: " + amount);
                                                                    Log.d(TAG, "remarks: " + remarks);

                                                                    apiService.payWithFace(token, ftoken, amount, remarks).enqueue(new Callback<PayingWithFaceReply>() {
                                                                        @Override
                                                                        public void onResponse(Call<PayingWithFaceReply> call, Response<PayingWithFaceReply> response) {
                                                                            PayingWithFaceReply payingWithFaceReply = response.body();
                                                                            if (payingWithFaceReply == null) {
                                                                                Toast.makeText(currentContext,
                                                                                        "payingWithFaceReply: " + payingWithFaceReply, Toast.LENGTH_SHORT).show();
                                                                                return;
                                                                            }
                                                                            if (payingWithFaceReply.code.equals("10001")) {
                                                                                String content = "刷脸收款成功  ¥" + amount + " " + getCurrentTime();
                                                                                model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {
                                                                                    BaiduSpeechClient.getInstance().speak("收款" + amount + "元");
                                                                                });
                                                                                showPrintDialog(payingWithFaceReply);
                                                                                print(payingWithFaceReply);
                                                                                Toast.makeText(currentContext, "支付状态：" + reply.msg, Toast.LENGTH_SHORT).show();
                                                                            } else {
                                                                                Toast.makeText(currentContext, reply.msg, Toast.LENGTH_SHORT).show();
                                                                            }
                                                                        }

                                                                        @Override
                                                                        public void onFailure(Call<PayingWithFaceReply> call, Throwable t) {
                                                                            Log.e(TAG, "t: " + t);
                                                                            Toast.makeText(currentContext, "未知错误：" + t, Toast.LENGTH_SHORT).show();
                                                                        }
                                                                    });
                                                                }

                                                                @Override
                                                                public void onFail(String errorCode) {
                                                                    Log.e(TAG, "verify --- errorCode: " + errorCode);
                                                                    switch (errorCode) {
                                                                        case ZolozConstants.ZOLOZ_ERROR_CODE_EXIT:
                                                                            Toast.makeText(currentContext, "已退出刷脸支付", Toast.LENGTH_SHORT).show();
                                                                            break;
                                                                        case ZolozConstants.ZOLOZ_ERROR_CODE_TIMEOUT:
                                                                            Toast.makeText(currentContext, "刷脸支付超时", Toast.LENGTH_SHORT).show();
                                                                            break;
                                                                        case ZolozConstants.ZOLOZ_ERROR_CODE_PAYMENT_METHOD_CHANGE:
                                                                            Toast.makeText(currentContext, "已退出刷脸支付，更改支付方式", Toast.LENGTH_SHORT).show();
                                                                    }
                                                                }
                                                            });
                                                        }

                                                        @Override
                                                        public void onFail(String errorCode, String errorMessage) {
                                                            Log.e(TAG, "getZimData --- errorCode: " + errorCode);
                                                            Log.e(TAG, "getZimData --- errorMessage: " + errorMessage);
                                                            if (errorCode == null)
                                                                Toast.makeText(currentContext, "无法获取服务器回应，请检查网络", Toast.LENGTH_SHORT).show();
                                                            else
                                                                Toast.makeText(currentContext, "刷脸支付失败，错误码：" + errorCode, Toast.LENGTH_SHORT).show();
                                                        }
                                                    });
                                        } else {
                                            Toast.makeText(currentContext, reply.msg, Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<AppAuthTokenGettingReply> call, Throwable t) {
                                        Log.e(TAG, "t: " + t);
                                        Toast.makeText(currentContext, "未知错误：" + t, Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public void onFail(String errorCode) {
                                Log.e(TAG, "errorCode: " + errorCode);
                                Toast.makeText(currentContext, "刷脸支付失败，错误码：" + errorCode, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
            }
        }
    };
    private static final String TAG = GeneralActivity.class.getSimpleName();
    private static final int SCAN_CODE = 100;//扫码requestCode
    private static final int SCAN_PAY_CODE = 101;//扫码付款
    private static final int BANK_CODE = 102;//银行卡收款  调起支付页面
    private RxPermissions permissions;//权限申请
    private BillViewModel model;
    private ProgressDialog dialog;
    private ProgressDialog bankDialog;
    private Intent bankIntent;
    private BankViewModel bankViewModel;

    private boolean scanPay = false;//是否是扫码收款

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_general;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, getResources().getColor(R.color.colorNavigationSelectColor));
        /****测试前置摄像头扫码付款，发布时注释****/
//        registerReceiver(scannedResultBroadcastReceiver, new IntentFilter("com.shengpaysdk.qrcode.scan"));
        /****************************************/
        //初始化打印机
        AidlUtil.getInstance().initPrinter();
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        bankViewModel = ViewModelProviders.of(this).get(BankViewModel.class);
        permissions = new RxPermissions(this);

        //设置点击事件
        dataBinding.collectionList.setOnClickListener(onMultiClickListener);
        dataBinding.norGatherToolbar.setNavigationOnClickListener(v -> {
            closeKeyBoard();
            onBackPressed();
        });
        dataBinding.collectionSearch.setOnClickListener(onMultiClickListener);
        dataBinding.sweep.setOnClickListener(onMultiClickListener);
        dataBinding.sweepReceive.setOnClickListener(onMultiClickListener);
        dataBinding.bankCardReceive.setOnClickListener(onMultiClickListener);
        dataBinding.receiveMoneyWithFaceTextView.setOnClickListener(onMultiClickListener);
        dataBinding.generalCount.setFilters(new InputFilter[]{new AmountFilter()});
        showKeyBoard(dataBinding.generalCount);
        if (SystemUtil.getSystemModel().contains("P1") || SystemUtil.getSystemModel().contains("A8")) {
            dataBinding.bankCardReceive.setVisibility(View.VISIBLE);
        } else {
            dataBinding.bankCardReceive.setVisibility(View.GONE);
        }
        //初始化参数  调起银行卡相关支付
        initIntent();
        //snackbar
        model.snackbarText.observe(this, s -> {
            if (s != null) {
                if (s.contains("等待用户支付超时") || s.contains("订单未支付")) {
                    showDepositDely(s);
                } else {
                    Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
                }
            }
        });
        //dialog
        model.dialogText.observe(this, s -> {
            if (s == null) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            } else {
                dialog = ProgressDialog.show(this, "正在交易...", s, false);
            }
        });
        //snackbar
        bankViewModel.snackText.observe(this, s -> {
            if (s != null) {
                if (s.contains("等待用户支付超时") || s.contains("订单未支付")) {
                    showDepositDely(s);
                } else
                    Snackbar.make(dataBinding.generalNoteLay, s, Snackbar.LENGTH_SHORT).show();
            }

        });
        //dialog
        bankViewModel.dialogText.observe(this, s -> {
            if (s == null) {
                if (bankDialog != null) {
                    bankDialog.dismiss();
                }
            } else {
                bankDialog = ProgressDialog.show(this, "请稍等...", s, false);
            }
        });
        alipayZoloz = AlipayZoloz.getInstance(this);
        merchantInfo = getMerchantInfo();
        alipayZoloz.install(merchantInfo);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        alipayZoloz.uninstall();
    }

    private HashMap getMerchantInfo() {
        HashMap merchantInfo = new HashMap();
        merchantInfo.put("merchantId", MERCHANT_ID);
        merchantInfo.put("partnerId", MERCHANT_ID);
        merchantInfo.put("appId", APP_ID);
        merchantInfo.put("deviceNum", DEVICE_NUMBER);
        return merchantInfo;
    }
    /****测试前置摄像头扫码付款，发布时注释****/
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        unregisterReceiver(scannedResultBroadcastReceiver);
//    }

    /****************************************/
    //显示支付超时dialog
    private void showDepositDely(String content) {

        ViewDialog dialog = new ViewDialog();
        dialog.setLayoutId(R.layout.deposit_dialog);
        dialog.showViewListener(view -> {
            TextView title = view.findViewById(R.id.accept_dialog_title);
            TextView ok = view.findViewById(R.id.ok);

            if (content.contains("等待用户支付超时")) {
                String result = String.valueOf(Html.fromHtml(content));
                int start = result.indexOf("(");
                int end = result.indexOf(")");
                SpannableStringBuilder spannableString = new SpannableStringBuilder(result);
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FE4655")),
                        start + 1, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

                title.setText(spannableString);
            } else if (content.contains("订单未支付")) {
                title.setText(content);
            }
            ok.setOnClickListener(v -> dialog.dismiss());
        });
        dialog.show(getSupportFragmentManager(), "0");
    }

    //显示键盘
    private void showKeyBoard(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager imm =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                Objects.requireNonNull(imm).showSoftInput(editText, 0);
                editText.setSelection(editText.getText().length());
            }
        }, 200);
    }

    //关闭软键盘
    private void closeKeyBoard() {
        InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        View view = getWindow().peekDecorView();
        if (view != null) {
            if (Objects.requireNonNull(manager).isActive()) {
                manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    //抽取各个交易类型公共的字段
    private void initIntent() {
        bankIntent = new Intent();
        bankIntent.setComponent(new ComponentName("com.shengpay.smartpos.shengpaysdk",
                "com.shengpay.smartpos.shengpaysdk.activity.MainActivity"));
        bankIntent.putExtra("appId", this.getPackageName());
    }

    //关闭软键盘
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            closeKeyBoard();
        }
        return super.onKeyDown(keyCode, event);
    }

    //将交易金额统一处理成12位，不足12位的在前面补0
    private String getAmount(String amount) {
        if (TextUtils.isEmpty(amount)) return null;
        while (amount.length() < 12) {
            amount = "0" + amount;
        }
        return amount;
    }

    private void startGather() {
        if (bankViewModel.bankBean != null) {
            //获取订单成功后
            BankBean.DataBean bean = bankViewModel.bankBean.get();
            if (bean != null) {
                String str = bean.getAmount();
                double du = Double.valueOf(str) * 100;
                int result = (int) du;
                Log.d(TAG, "getInfo: 最后金额结果:" + result);
                bankIntent.putExtra("barcodeType", "0");//指定为银行卡消费
                bankIntent.putExtra("amount", getAmount(String.valueOf(result)));//交易金额
                bankIntent.putExtra("orderNoSFT", bean.getOut_trade_no());//交易订单号
                bankIntent.putExtra("transName", "0");//交易订单号


                //用户联备注
                bankIntent.putExtra("printMerchantInfo",
                        "交易订单号:" + bean.getOut_trade_no() + "        "
                                + "\n交易备注: " + "银行卡押金收款");
                bankIntent.putExtra("printMerchantInfo2", bean.getOut_trade_no());
                bankIntent.putExtra("priInfo", "交易订单号:" + bean.getOut_trade_no() + "        "
                        + "\n交易备注: " + "银行卡押金收款");
                bankIntent.putExtra("priInfo2", bean.getOut_trade_no());
                //判断是否安装盛付通支付
                if (isInstallShengfuPay()) {
                    startActivityForResult(bankIntent, BANK_CODE);
                } else {
                    Toast.makeText(this, "请前往应用市场下载盛付通支付!", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    //判断是否安装盛付通支付sdk
    private boolean isInstallShengfuPay() {
        PackageManager packageManager = getPackageManager();
        List<PackageInfo> list = packageManager.getInstalledPackages(0);
        for (int i = 0; i < list.size(); i++) {
            if (SystemUtil.getSystemModel().equals("P1") || SystemUtil.getSystemModel().equals("P1_4G") || SystemUtil.getSystemModel().contains("A8")) {
                if (list.get(i).packageName.equalsIgnoreCase("sunmi.fw2.payment.shengpay") ||
                        list.get(i).packageName.equalsIgnoreCase("sunmimi.payment.shengpay") ||
                        list.get(i).packageName.equalsIgnoreCase("com.shengpay.smartpos.shengpaysdk")) {
                    return true;
                }
            }
            Log.i(TAG, "isInstallShengfuPay: 包名：" + list.get(i).packageName);
        }
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //处理二维码扫描结果
        if (requestCode == SCAN_CODE && data != null) {
            Bundle bundle = data.getExtras();
            if (bundle == null) return;

            dealWithScanResult(bundle);
        }
        //当为扫码付款时
        if (requestCode == SCAN_PAY_CODE && data != null) {
            Bundle bundle = data.getExtras();
            scanPay(bundle);
        }
        //这里处理银行卡收款  相关  交易成功 交易失败  进行回调
        if (requestCode == BANK_CODE && data != null) {
            Bundle extras1 = data.getExtras();
            bankPay(resultCode, extras1, data);
        }
    }

    /**
     * 处理二位扫描结果  查询订单
     *
     * @param bundle bundle
     */
    private void dealWithScanResult(Bundle bundle) {
        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
            String result = bundle.getString(CodeUtils.RESULT_STRING);
            Log.d(TAG, "result: " + result);
            if (result == null) {
                return;
            }
            boolean strHead = result.contains("fu");
            Log.d(TAG, "onActivityResult: 小票抬头是fu开头：" + strHead + "结果:" + result);
            if (result.startsWith("fu")) {//当时预授权订单时

                Intent intent = new Intent(GeneralActivity.this, AutTncActivity.class);
                intent.putExtra("orderId", result);
                startActivity(intent);

            } else {//否则是收款订单  或者分期订单   预授权结算后直接变成普通订单

                Intent intent = new Intent(GeneralActivity.this, CollAndInstallDetailActivity.class);
                intent.putExtra("orderId", result);
                startActivity(intent);
            }

        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
            Toast.makeText(GeneralActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
        }
    }

    //扫描二维码收款
    private void scanPay(Bundle bundle) {
        if (bundle == null) return;
        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
            String result = bundle.getString(CodeUtils.RESULT_STRING);
            if (result == null) {
                return;
            }
            //改变状态
            scanPay = true;
            //提交二维码扫描生成订单
            model.scanPay(dataBinding.generalNote.getText().toString(), result,
                    dataBinding.generalCount.getText().toString(), null, () -> {
                        dialog.dismiss();
                        //生成订单后 结束显示dialog
                        ScanPayBean scanPayBean = model.scanPay.get();
                        //支付成功后打印
                        if (scanPayBean != null) {
                            print(scanPayBean);
                            String content = "普通收款成功  ¥" + dataBinding.generalCount.getText().toString() + " " + getCurrentTime();
                            model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {
                                BaiduSpeechClient.getInstance().speak("收款" + dataBinding.generalCount.getText().toString().toString() + "元");
                            });
                            //显示打印dialog
                            showPrintDialog(scanPayBean);
                        }
                    });
            Log.d(TAG, "onActivityResult: 解析结果:" + result);
        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
            Toast.makeText(GeneralActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
        }
    }

    private void showPrintDialog(PayingWithFaceReply payingWithFaceReply) {
        ViewDialog viewDialog = new ViewDialog();
        viewDialog.setLayoutId(R.layout.print_dialog);
        viewDialog.showViewListener(view -> {
            TextView title = view.findViewById(R.id.cancel_dialog_title);
            title.setText("收款成功,是否打印小票?");
            TextView print = view.findViewById(R.id.cancel_yes);
            TextView cancel = view.findViewById(R.id.cancel_no);
            print.setOnClickListener(new OnMultiClickListener() {
                @Override
                public void onMultiClick(View view) {
                    print(payingWithFaceReply);
                }
            });
            cancel.setOnClickListener(v -> {
                viewDialog.dismiss();
              /*  //跳转到收款详情
                Intent intent = new Intent(GeneralActivity.this, CollAndInstallDetailActivity.class);
                intent.putExtra("orderId", scanPayBean.getOut_trade_no());
                intent.putExtra("needPrint", false);
                startActivity(intent);*/
            });
        });
        viewDialog.show(getSupportFragmentManager(), "0");
    }

    //显示打印dialog
    private void showPrintDialog(ScanPayBean scanPayBean) {
        ViewDialog viewDialog = new ViewDialog();
        viewDialog.setLayoutId(R.layout.print_dialog);
        viewDialog.showViewListener(view -> {
            TextView title = view.findViewById(R.id.cancel_dialog_title);
            title.setText("收款成功,是否打印小票?");
            TextView print = view.findViewById(R.id.cancel_yes);
            TextView cancel = view.findViewById(R.id.cancel_no);
//            print.setOnClickListener(v -> {
//                print(scanPayBean);
//            });

            print.setOnClickListener(new OnMultiClickListener() {
                @Override
                public void onMultiClick(View view) {
                    print(scanPayBean);
                }
            });
            cancel.setOnClickListener(v -> {
                viewDialog.dismiss();
              /*  //跳转到收款详情
                Intent intent = new Intent(GeneralActivity.this, CollAndInstallDetailActivity.class);
                intent.putExtra("orderId", scanPayBean.getOut_trade_no());
                intent.putExtra("needPrint", false);
                startActivity(intent);*/
            });
        });
        viewDialog.show(getSupportFragmentManager(), "0");
    }

    private void print(PayingWithFaceReply payingWithFaceReply) {
        List<String> contentsToPrint = payingWithFaceReply.data.print_array;
        String paymentMethod = contentsToPrint.get(0);
        String filename = null;
        switch (paymentMethod) {
            case "0":
                filename = "icon_alipay.bmp";
                break;
            case "1":
                filename = "icon_union.bmp";
                break;
            case "2":
                filename = "icon_wechat.bmp";
        }
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open(filename));
            AidlUtil aidlUtil = AidlUtil.getInstance();
            aidlUtil.printBitmap(bitmap, "0", "2", 0);
            aidlUtil.printText(contentsToPrint.get(1) + '\n', "32", "32",
                    "1", true, false);
            aidlUtil.printText(contentsToPrint.get(2) + '\n', "24", "24",
                    "1", false, false);
            String paymentMethodAndMore = contentsToPrint.get(3);
            paymentMethodAndMore = paymentMethodAndMore.replace("\\n", "\n");
            aidlUtil.printText(paymentMethodAndMore, "24", "24",
                    "0", false, false);
            String collection = contentsToPrint.get(6);
            collection = collection.replace("\\n", "\n");
            aidlUtil.printText(collection, "24", "24",
                    "0", false, false);
            String remarks = contentsToPrint.get(7);
            remarks = remarks.replace("\\n", "\n");
            aidlUtil.printText(remarks, "24", "24",
                    "0", false, false);
            aidlUtil.printQr(contentsToPrint.get(8), "6", "3");
            String cashierAndPrintingTime = contentsToPrint.get(9);
            cashierAndPrintingTime = cashierAndPrintingTime.replace("\\n", "\n");
            aidlUtil.printText(cashierAndPrintingTime, "24", "24",
                    "0", false, false);
            String last = contentsToPrint.get(10);
            last = last.replace("\\n", "\n");
            aidlUtil.printText(last + '\n', "24", "24",
                    "1", false, false);
            aidlUtil.cutPaper(null);
//                                                                                    aidlUtil.printBitmapForT2(bitmap, PrintCommands.ALIGNMENT_LEFT, callback);
//                                                                                    aidlUtil.printTextForT2(contentsToPrint.get(1) + '\n', 1, 2,
//                                                                                            PrintCommands.ALIGNMENT_CENTER, callback);
//                                                                                    aidlUtil.printTextForT2(contentsToPrint.get(2) + '\n', 1, 1,
//                                                                                            PrintCommands.ALIGNMENT_CENTER, callback);
//                                                                                    aidlUtil.printTextForT2(contentsToPrint.get(3) + '\n', 1, 1,
//                                                                                            PrintCommands.ALIGNMENT_LEFT, callback);
//                                                                                    aidlUtil.printTextForT2(contentsToPrint.get(6) + '\n', 1, 2,
//                                                                                            PrintCommands.ALIGNMENT_LEFT, callback);
//                                                                                    aidlUtil.printTextForT2(contentsToPrint.get(7) + '\n', 1, 1,
//                                                                                            PrintCommands.ALIGNMENT_LEFT, callback);
//                                                                                    aidlUtil.printQRCodeForT2(contentsToPrint.get(8), 7,
//                                                                                            PrintCommands.ALIGNMENT_CENTER, callback);
//                                                                                    aidlUtil.printTextForT2("\n", 1, 1,
//                                                                                            PrintCommands.ALIGNMENT_CENTER, callback);
//                                                                                    aidlUtil.printTextForT2(contentsToPrint.get(9) + '\n', 1, 1,
//                                                                                            PrintCommands.ALIGNMENT_LEFT, callback);
//                                                                                    aidlUtil.printTextForT2(contentsToPrint.get(10) + '\n', 1, 1,
//                                                                                            PrintCommands.ALIGNMENT_CENTER, callback);


        } catch (IOException ex) {
            Log.e(TAG, null, ex);
        }
    }

    //打印
    private void print(ScanPayBean scanPayBean) {
        if (scanPayBean == null) {
            return;
        }
        List<String> printContent = Objects.requireNonNull(scanPayBean).getPrint_array();
        String bitmapType = printContent.get(0);
        AidlUtil aidlUtil = AidlUtil.getInstance();
        aidlUtil.enterPrinterBuffer(true);
        //打印支付方式图标
        commenPrint(printContent, aidlUtil, bitmapType);
//        //打印支付方式图标
//        if (SystemUtil.getSystemModel().contains("A8")) {
//            aidlUtil.printBitmapForA8(bitmapType, 2);
//        } else {
//            int resId = getResId(bitmapType);
//            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
//            aidlUtil.printBitmap(bitmap, "2", "2", resId);
//        }
//        //抬头
//        aidlUtil.printText(printContent.get(1), "32", "32", "1",
//                true, false);
//        aidlUtil.printBlankLine("1", "10");
//        //门店
//        aidlUtil.printText(printContent.get(2), "24", "24", "1",
//                false, false);
//        //订单支付方式text开始
//        aidlUtil.printText(printContent.get(3).replace("\\n", "\n"),
//                "24", "24", "0",
//                false, false);
//        //业务记录
//        aidlUtil.printText(printContent.get(4), "32", "32", "0",
//                true, false);
//        //业务记录内容
//        if (!TextUtils.isEmpty(printContent.get(5))){
//            aidlUtil.printText("\n" + printContent.get(5)
//                            .replace("\\n", "\n"), "24", "24", "0",
//                    false, false);
//        }
//
//
//        //退款 ||收款
//        aidlUtil.printText( printContent.get(6), "32", "32", "0",
//                true, false);
//        //退款获取收款内容
//        aidlUtil.printText("\n" + printContent.get(7)
//                        .replace("\\n", "\n"), "24", "24", "0",
//                false, false);
//        aidlUtil.printBlankLine("1", "10");
//        //打印二维码
//        aidlUtil.printQr(printContent.get(8), "8", "3");
//        //收银员   //打印时间
//        aidlUtil.printText(printContent.get(9).replace("\\n", "\n"),
//                "24", "24", "0", false, false);
//        aidlUtil.printBlankLine("1", "10");
//        aidlUtil.printText(printContent.get(10).replace("\\n", "\n"),
//                "24", "24", "1", false, false);
//        aidlUtil.printText("\n" + printContent.get(11).replace("\\n", "\n"),
//                "24", "24", "1", false, false);
//        aidlUtil.printText(printContent.get(12),
//                "24", "24", "1", false, false);
//        aidlUtil.printBlankLine("5", "30");
//        aidlUtil.printCommit();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        InputMethodManager imm = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && imm.isActive()) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
            return true;
        } else {
            return super.onTouchEvent(event);
        }
    }

    //获取当前时间
    private String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        simpleDateFormat.applyPattern("MM-dd HH:mm:SS");

        return simpleDateFormat.format(new Date());
    }

    //处理银行卡收款相关
    private void bankPay(int resultCode, Bundle extras1, Intent data) {
        boolean success = false;//是否交易成功
        if (extras1 == null) {
            return;
        }
        String payResult = null;//交易结果
        Set<String> keySet = extras1.keySet();
        switch (resultCode) {
            case Activity.RESULT_OK:
                Toast.makeText(GeneralActivity.this, "交易成功", Toast.LENGTH_SHORT).show();
                success = true;

                StringBuilder resultBuilder = new StringBuilder();
                for (String s : keySet) {
                    String str = s + ":" + extras1.getString(s) + ",";
                    resultBuilder.append(str);

                }
                Log.d(TAG, "onActivityResult: 支付结果：" + resultBuilder.toString());
                payResult = resultBuilder.toString();
                //推送交易结果
                String content = "银行卡普通收款成功  ¥" + dataBinding.generalCount.getText().toString() + " " + getCurrentTime();
                model.startGt(ISharedPreference.getInstance(getApplication()).getCid(), "天择可付推送提醒", content, () -> {
                    BaiduSpeechClient.getInstance().speak("收款" + dataBinding.generalCount.getText().toString().toString() + "元");
                });
                break;
            case Activity.RESULT_CANCELED:
                success = false;
                String reason = data.getStringExtra("reason");
                Toast.makeText(GeneralActivity.this, reason, Toast.LENGTH_SHORT).show();

                StringBuilder failBuilder = new StringBuilder();
                for (String s : keySet) {
                    String str = s + ":" + extras1.getString(s) + ",";
                    failBuilder.append(str);

                }
                payResult = failBuilder.toString();
                break;

        }
        Log.d(TAG, "onActivityResult:payResult :普通收款交易信息:=============" + payResult);
        //上传交易结果
        //回调上传交易结果
        boolean finalSuccess = success;
        bankViewModel.uploadTradeInfo(payResult, () -> {
            if (finalSuccess) {//如果交易成功再跳转
                Intent intent = new Intent(GeneralActivity.this, CollAndInstallDetailActivity.class);
                intent.putExtra("orderId", bankViewModel.bankBean.get().getOut_trade_no());
                intent.putExtra("needPrint", true);
                startActivity(intent);

            }
            Log.d(TAG, "bankPay: 上传交易信息成功!");
        });
    }

    /**
     * 申请二维码扫描需要的权限
     */
    @SuppressLint("CheckResult")
    private void requestScanPermission(int code) {
        permissions.requestEach(Manifest.permission.CAMERA).subscribe(permission -> {

            if (permission.granted) {
                scanCode(code);
            } else if (permission.shouldShowRequestPermissionRationale) {
                Toast.makeText(GeneralActivity.this, "扫描二维码需要相机权限!", Toast.LENGTH_SHORT).show();

            } else {
                Uri packageURI = Uri.parse("package:" + GeneralActivity.this.getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);

            }
        });
    }

    //开始扫描二维码
    private void scanCode(int code) {
        Intent scanIntent = new Intent(GeneralActivity.this, ScanActivity.class);
        startActivityForResult(scanIntent, code);
    }
}
